package com.cjm.one.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cjm.one.goods.mapper.GoodsCommentTagListMapper;
import com.cjm.one.goods.mapper.GoodsCommentTagMapper;
import com.cjm.one.goods.service.GoodsCommentService;
import com.cjm.one.goods.mapper.GoodsCommentMapper;
import com.cjm.one.model.goods.dto.GoodsCommentDto;
import com.cjm.one.model.goods.entity.GoodsComment;
import com.cjm.one.model.goods.entity.GoodsCommentTag;
import com.cjm.one.model.goods.entity.GoodsCommentTagList;
import com.cjm.one.model.goods.vo.GoodsCommentCountVo;
import com.cjm.one.model.goods.vo.GoodsCommentTagVo;
import com.cjm.one.model.goods.vo.GoodsCommentVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
* @author 29289
* @description 针对表【goods_comment】的数据库操作Service实现
* @createDate 2024-09-05 16:07:00
*/
@Service
@Slf4j
public class GoodsCommentServiceImpl extends ServiceImpl<GoodsCommentMapper, GoodsComment>
    implements GoodsCommentService{

    @Resource
    private GoodsCommentMapper goodsCommentMapper;
    @Resource
    private GoodsCommentTagMapper goodsCommentTagMapper;
    @Resource
    private GoodsCommentTagListMapper goodsCommentTagListMapper;
    @Override
    public Page<GoodsComment> findList(Long current, Long size, Long userId, String text, Long goodsId) {
        Page<GoodsComment> page = new Page<>(current, size);
        LambdaQueryWrapper<GoodsComment> goodsCommentLambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (userId != null)
        {
            goodsCommentLambdaQueryWrapper.eq(GoodsComment::getUserId, userId);
        }
        if (text != null)
        {
            goodsCommentLambdaQueryWrapper.like(GoodsComment::getContent, text);
        }
        if (goodsId != null){
            goodsCommentLambdaQueryWrapper.eq(GoodsComment::getGoodsId, goodsId);
        }
        goodsCommentLambdaQueryWrapper.orderByDesc(GoodsComment::getCreateTime, GoodsComment::getId);
        return goodsCommentMapper.selectPage(page, goodsCommentLambdaQueryWrapper);
    }

    @Override
    public GoodsCommentVo getCommentById(Long id) {
        GoodsCommentVo commentVo = goodsCommentMapper.selectByCommentId(id);
        return commentVo;
    }



    @Override
    public GoodsCommentCountVo getCommentTagById(Long id) {
        GoodsCommentCountVo goodsCommentCountVo = new GoodsCommentCountVo();
        // 1. 获取标签统计数据
        List<GoodsCommentTagVo> tags = goodsCommentTagMapper.getCommentTagById(id);
        goodsCommentCountVo.setTags(tags);

        // 2. 构建评论查询条件
        LambdaQueryWrapper<GoodsComment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsComment::getGoodsId, id)
                .select(GoodsComment::getScore); // 只查询评分字段

        // 3. 获取评分列表和总数
        List<GoodsComment> comments = goodsCommentMapper.selectList(queryWrapper);
        Long total = (long) comments.size();
        goodsCommentCountVo.setCount(total);

        // 4. 计算平均分（保留1位小数）
        if (total > 0) {
            goodsCommentCountVo.setScore(Optional.ofNullable(goodsCommentMapper.getAverageScore(id))
                    .map(avg -> (int) Math.round(avg))
                    .orElse(0));// 或保留小数
        } else {
            goodsCommentCountVo.setScore(0); // 默认0分
        }

        return goodsCommentCountVo;
    }

    @Override
    public Page<GoodsCommentVo> getCommentPage(Page<GoodsCommentVo> page, Long goodsId,
                                               String sortOrder, List<Long> tagIds) {
        return baseMapper.selectCommentPage(page, goodsId,sortOrder, tagIds);
    }

    @Override
    public List<GoodsCommentTag> getTags() {
        List<GoodsCommentTag> goodsCommentTags = goodsCommentTagMapper.selectList(null);
        return goodsCommentTags;
    }

    @Override
    public Boolean saveGoodsComment(List<GoodsCommentDto>  goodsCommentDto) {
        // 检查是否有评论数据
        if (goodsCommentDto == null || goodsCommentDto.isEmpty()) {
            return false; // 如果没有评论数据，返回 false
        }

        // 创建 GoodsComment 列表
        List<GoodsComment> goodsComments = new ArrayList<>();
        goodsCommentDto.stream().forEach(item -> {
            GoodsComment goodsComment = new GoodsComment();
            BeanUtils.copyProperties(item, goodsComment);
            goodsComments.add(goodsComment);
        });
        log.info("goodsComments:{}", goodsComments);
        // 批量插入评论
        goodsCommentMapper.insertBatch(goodsComments);

        // 获取插入后的评论ID并插入评论标签
        for (int i = 0; i < goodsCommentDto.size(); i++) {
            GoodsCommentDto goodsCommentDtoItem = goodsCommentDto.get(i);
            Long commentId = goodsComments.get(i).getId(); // 获取插入后的评论ID

            // 处理标签
            List<GoodsCommentTagList> tagNames = goodsCommentDtoItem.getTagNames();
            if (tagNames != null && !tagNames.isEmpty()) {
                tagNames.forEach(tag -> {
                    tag.setCommentId(commentId); // 设置评论ID
                    tag.setGoodsId(goodsCommentDtoItem.getGoodsId()); // 设置商品ID
                    tag.setUserId(goodsCommentDtoItem.getUserId()); // 设置用户ID
                });

                // 批量插入标签
                goodsCommentTagListMapper.insertBatch(tagNames);
            }
        }

        return true; // 返回成功

    }


}







